package reduce.fz.com.reduce.util.http;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.VolleyError;

import java.net.HttpURLConnection;

/**
 * 重新实现retryPolicy ， 实现了 feel image domain 和ip 切换
 *
 * @auth lipf on 2014/12/30.
 */
public class FeelImageRetryPolicy extends DefaultRetryPolicy {

    /**
     * The default socket timeout in milliseconds
     */
    public static final int DEFAULT_TIMEOUT_MS = 2300;

    /**
     * The default number of retries
     */
    public static final int DEFAULT_MAX_RETRIES = 1;

    /**
     * The default backoff multiplier
     */
    public static final float DEFAULT_BACKOFF_MULT = 1f;

    /**
     * 检测domain 或者IP错的时候用来重试请求的，因为changeDomainIP必须要在 getUrl 之前调用否则无效
     */
    private ImageRequest imageRequest;

    public FeelImageRetryPolicy(ImageRequest imageRequest) {
        super(DEFAULT_TIMEOUT_MS, DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT);
        this.imageRequest = imageRequest;
    }

    /**
     * 计算retry的次数，方式太多次的重试
     */
    private int retry_count = 0;

    public void retry(VolleyError error) throws VolleyError {
//        super.retry(error);
        retry_count++;
        if (error == null || error.networkResponse == null) { // feel 链接错误
            if (retry_count >= 3) {
                super.retry(error);
            }
            imageRequest.changeDomainIP();
        } else {
            int statusCode = error.networkResponse.statusCode;
            if (statusCode == HttpURLConnection.HTTP_CLIENT_TIMEOUT || statusCode == HttpURLConnection.HTTP_GATEWAY_TIMEOUT || statusCode == HttpURLConnection.HTTP_BAD_GATEWAY || statusCode == HttpURLConnection.HTTP_UNAVAILABLE) {
                if (retry_count >= 3) {
                    super.retry(error);
                }
                imageRequest.changeDomainIP();
            } else {
                super.retry(error);
            }
        }
    }

}
